package com.virtudroid.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.virtudroid.domain.WavHeaderInfo;
import com.virtudroid.util.WavHeaderReaderUtil;

public class SimpleWavReader implements OnClickListener {

	private AudioTrack audioTrack;
	
	@Override
	public void onClick(View v) {
		// Read the file header to a byte buffer
		InputStream wavInputStream;
		try {
			wavInputStream = new FileInputStream(new File("/sdcard/goldeneye.wav"));
		} catch (FileNotFoundException e) {
			Log.e("SimpleWavReader", "Could not find wav file", e);
			// TODO handle exception
			return;
		}
		
		WavHeaderInfo wavHeaderInfo = new WavHeaderReaderUtil(wavInputStream).readInfos();
	    
	    int channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
	    if (wavHeaderInfo.getNumChannels() == 1)
	    	channelConfig = AudioFormat.CHANNEL_OUT_MONO;
		
		audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, wavHeaderInfo.getSampleRate(), channelConfig, AudioFormat.ENCODING_PCM_16BIT, AudioTrack.getMinBufferSize(wavHeaderInfo.getSampleRate(), channelConfig, AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
		byte[] audioData = new byte[wavHeaderInfo.getSubchunk2Size()];
		try {
			wavInputStream.read(audioData, 0, audioData.length);
		} catch (IOException e) {
			Log.e("SimpleWavReader", "Can not read wav file data", e);
			// TODO handle exception
		}
		audioTrack.play();
		audioTrack.write(audioData, 0, audioData.length);
	}
}
